<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\controller\api\v1\store;

use app\jobs\user\UserBelongStoreJob;
use app\services\order\StoreCartServices;
use app\services\store\SystemStoreServices;
use app\services\store\SystemStoreStaffServices;
use app\Request;

/**
 * Class Store
 * @package app\controller\api\v1\store
 */
class Store
{
    protected $services;

    public function __construct(SystemStoreServices $services)
    {
        $this->services = $services;
    }

	/**
	 * 	根据进店规则返回与哦那个户进入门店ID
	 * @param Request $request
	 * @return \think\Response
	 */
	public function getUserEntryStore(Request $request)
	{
		$param = $request->getMore([
			['latitude', ''],//经纬度
			['longitude', ''],//经纬度
			[['store_id', 'd'], 0],//带参门店ID
			[['select_store_id', 'd'], 0],//用户切换选中门店ID
		]);
		$uid = 0;
		if ($request->hasMacro('uid')) $uid = (int)$request->uid();
		$param['ip'] = $request->ip();
		return app('json')->success($this->services->getStoreIdByEntryRules($uid, $param, true));
	}

	/**
	 * 首页diy获取门店列表
	 * @param Request $request
	 * @return \think\Response
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function getHomeStoreList(Request $request)
	{
		[$store_type, $keywords, $latitude, $longitude, $province, $city, $area, $street, $product_num, $store_id] = $request->getMore([
			['store_type', 1],
			['keyword', ''],
			['latitude', ''],
			['longitude', ''],
			['province', 0],
			['city', 0],
			['area', 0],
			['street', 0],
			['product_num', 4],//商品数量
			['store_id', 0]
		], true);
		$uid = 0;
		if ($request->hasMacro('uid')) $uid = (int)$request->uid();

		if (!checkCoordinates($longitude, $latitude)) {
			return app('json')->fail('参数错误');
		}
		$storeList = [];
		//开启门店 && 不是单店模式
		if (sys_config('store_func_status', 1)) {
			$where = ['store_type' => $store_type, 'keywords' => $keywords, 'province' => $province, 'city' => $city, 'area' => $area, 'street' => $street];
			$entryRules = $this->services->getStoreIdByEntryRules($uid, ['latitude' => $latitude, 'longitude' => $longitude]);
			$store_id = $entryRules['store_id'] ?? 0;
			if ($store_id) {
				$storeInfo = $this->services->get($store_id, ['id', 'is_alone']);
				if ($storeInfo && $storeInfo['is_alone']) {//进入的是隔离门店
					$where['id'] = $store_id;
				}
			}
			if (sys_config('shop_operation_type', 1) == 1) {//平台+多店模式
				if (!isset($where['id'])) {//未进入隔离门店 查询当前区域门店
					$ids = $this->services->getRegionStoreIds((int)$store_id);
					if ($ids) $where['ids'] = $ids;
					//去除隔离门店
					$where['is_alone'] = 0;
				}
			} else {
				if ($store_id) {
					$where['id'] = $store_id;
				}
			}
			$storeList = $this->services->getHomeStoreList($uid, $where, $latitude, $longitude, '', 0, (int)$product_num);
		}
		return app('json')->success($storeList);
	}

	/**
 	* 附近门店
	* @param Request $request
	* @param SystemStoreServices $services
	* @param StoreCartServices $cartServices
	* @return mixed
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	 */
    public function nearbyStore(Request $request, SystemStoreServices $services, StoreCartServices $cartServices)
    {
        [$latitude, $longitude, $store_id] = $request->getMore([
            ['latitude', ''],
            ['longitude', ''],
            ['store_id', 0]//选择具体门店
        ], true);
		$where = [];
		if ((int)$store_id) {
			$where['id'] = $store_id;
		}
		if (!checkCoordinates($longitude, $latitude)) {
			return app('json')->fail('参数错误');
		}
		$storeStatus = sys_config('store_func_status', 1);
		$storeInfo = [];
		//开启门店
		if ($storeStatus) {
			$storeInfo = $services->getNearbyStore($where, $latitude, $longitude, $request->ip(), 1);
		}
        $data['info'] = $storeInfo;
        $data['tengxun_map_key'] = sys_config('tengxun_map_key');
		$data['store_splicing_switch'] = $storeStatus && sys_config('store_splicing_switch');
        $data['store_self_mention'] = sys_config('store_self_mention', 0);
		$uid = $request->hasMacro('uid') ? (int)$request->uid() : 0;
		//访问某个特定门店
		if ($storeInfo && isset($where['id']) && $where['id']) {
			UserBelongStoreJob::dispatchDo('setVisitStore', [$uid, $storeInfo['id'], ['ip' => $request->ip()]]);
		}
		$data['cart_num'] = 0;
		if ($uid && $data['info']) {
			$cartArr = $cartServices->getUserCartCount($uid, ['status' => 1, 'staff_id' => 0, 'store_id' => $data['info']['id'] ?? 0], 0);
			$data['cart_num'] = $cartArr['count'] ?? 0;
		}
        return app('json')->successful($data);
    }

	/**
	* 获取门店列表
	* @param Request $request
	* @return mixed
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	 */
	public function getStoreList(Request $request)
	{
		[$store_type, $keywords, $latitude, $longitude, $province, $city, $area, $street, $product_id, $store_id, $is_select] = $request->getMore([
			['store_type', 1],
			['keyword', ''],
            ['latitude', ''],
            ['longitude', ''],
            ['province', 0],
            ['city', 0],
            ['area', 0],
            ['street', 0],
			['product_id', 0],//商品ID
			['store_id', 0],//门店ID
			['is_select', 0],//首页选择切换门店
        ], true);
		if (!checkCoordinates($longitude, $latitude)) {
			return app('json')->fail('参数错误');
		}
		$uid = (int)$request->uid();
		$where = ['uid' => $uid, 'store_type' => $store_type, 'keywords' => $keywords, 'province' => $province, 'city' => $city, 'area' => $area, 'street' => $street];
		$storeList = [];
		//开启门店
		if (sys_config('store_func_status', 1)) {
			$entryRules = $this->services->getStoreIdByEntryRules($uid, ['latitude' => $latitude, 'longitude' => $longitude]);
			$entryStoreId = $entryRules['store_id'] ?? 0;
			if ($entryStoreId) {
				$storeInfo = $this->services->get($entryStoreId, ['id', 'is_alone']);
				if ($storeInfo && $storeInfo['is_alone']) {//进入的是隔离门店
					$where['id'] = $entryStoreId;
				}
			}
			if ($is_select || sys_config('shop_operation_type', 1) == 1) {//切换门店 || 多门店+平台模式
				if (!isset($where['id'])) {//未进入隔离门店 查询当前区域门店
					$ids = $this->services->getRegionStoreIds((int)$entryStoreId);
					if ($ids) $where['ids'] = $ids;
					//去除隔离门店
					$where['is_alone'] = 0;
				}
				$storeList = $this->services->getNearbyStore($where, $latitude, $longitude, '', 0, (int)$product_id, (int)$store_id);
			} else {
				$shop_operation_type = $entryRules['shop_operation_type'] ?? 1;
				if (in_array($shop_operation_type, [2, 3])) {
					$store_id = $entryStoreId;
				}
				$storeList = $this->services->getNearbyStore($where, $latitude, $longitude, '', 0, (int)$product_id, (int)$store_id);
			}
		}
		return app('json')->success($storeList);
	}

	/**
 	* 获取门店客服列表
	* @param SystemStoreStaffServices $staffServices
	* @param $store_id
	* @return mixed
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	 */
	public function getCustomerList(SystemStoreStaffServices $staffServices, $store_id)
	{
		$customer = [];
		if ($store_id) {
			$customer = $staffServices->getCustomerList((int)$store_id, 'id,store_id,staff_name,avatar,customer_phone,customer_url');
		}
		return app('json')->success($customer);
	}

	/**
 	* 获取客服详情
	* @param SystemStoreStaffServices $staffServices
	* @param $id
	* @return mixed
	* @throws \think\db\exception\DataNotFoundException
	* @throws \think\db\exception\DbException
	* @throws \think\db\exception\ModelNotFoundException
	 */
	public function getCustomerInfo(SystemStoreStaffServices $staffServices, $id)
	{
		$info = [];
		if (!$id) {
			return app('json')->fail('缺少参数');
		}
		$info = $staffServices->getStaffInfo((int)$id, 'id,store_id,staff_name,avatar,customer_phone,customer_url');
		if (!$info) {
			return app('json')->fail('客服不存在');
		}
		$info = $info->toArray();
		$storeInfo = $this->services->getStoreInfo((int)$info['store_id']);
		$info['store_name'] = $storeInfo['name'] ?? '';
		$info['address'] = $storeInfo['address'] ?? '';
		$info['detailed_address'] = $storeInfo['detailed_address'] ?? '';
		$info['latitude'] = $storeInfo['latitude'] ?? '';
		$info['longitude'] = $storeInfo['longitude'] ?? '';
		$info['day_time'] = $storeInfo['day_time'] ?? '';
		$info['day_start'] = $storeInfo['day_start'] ?? '';
		$info['day_end'] = $storeInfo['day_end'] ?? '';
		return app('json')->success($info);
	}

}
